package cn.wowjoy.office.materialinspection.xunjian.detail;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.model.GlideUrl;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.common.adapter.DeviceDetailPhotoAdapter;
import cn.wowjoy.office.common.adapter.MLinearLayoutManager;
import cn.wowjoy.office.common.widget.AlphaManager;
import cn.wowjoy.office.common.widget.CheckImgvPop;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.common.widget.PhotoPreviewDialog;
import cn.wowjoy.office.data.constant.Constants;
import cn.wowjoy.office.data.request.InspectRecordControllerRequest;
import cn.wowjoy.office.data.response.InspectRecordControllerResponse;
import cn.wowjoy.office.data.response.InspectTaskDtlVO;
import cn.wowjoy.office.data.response.InspectTaskSelect;
import cn.wowjoy.office.data.response.SingleTaskController;
import cn.wowjoy.office.databinding.ActivityDeviceDetail2Binding;
import cn.wowjoy.office.pm.data.UploadImgResponse;
import cn.wowjoy.office.pm.view.PMBaseActivity;
import cn.wowjoy.office.utils.ImageSelectorUtils;
import cn.wowjoy.office.utils.MD5Util;
import cn.wowjoy.office.utils.MyTextWatcher;
import cn.wowjoy.office.utils.PreferenceManager;
import cn.wowjoy.office.utils.ToastUtil;
import cn.wowjoy.office.utils.dialog.DialogUtils;

public class DeviceDetail2Activity extends PMBaseActivity<ActivityDeviceDetail2Binding, DeviceDetailViewModel> implements View.OnClickListener {
    private static final int REQUEST_CODE = 0x00000011;
    // 选择结果
    public String result;
    public final int RESULT_OK = 0;
    public final int RESULT_FAIL = 1;
    public final int RESULT_NOTSUIT = 2;
    String key = "";
    boolean isDone;
    public InspectTaskDtlVO inspectTaskDtlVO;
    SingleTaskController single;
    boolean isShow;  //  是扫码进入的详情页  还是 手点进来的

    boolean isLocal = false; // 是本地图片 还是网络图片
    boolean isDelete = false; // 是否是删除图片

    private CheckImgvPop checkImgvPop;
    // 单图片路径
    public String filePath;
    InspectRecordControllerRequest request;
    private ArrayList<String> imagePaths;
    private boolean isSecond = false; // 是否第二次编辑
    private boolean isEdit = false;

    private boolean isFind; //是否找到广播对应
    private List<String> mStrings;

    public String taskDtlId;
    public String totalId;

    public String qrCode;
    private MDialog mDialog;//提交
    private PhotoPreviewDialog mPhotoPreviewDialog;


    private UploadImgResponse imgRequest; //原图 缩略图ID
    private PictureBean pictureBean; //Adapter实体类

    //单项选择 标题
    String[] XJNR = new String[]{"外观检查", "标签齐全", "功能检查", "设备清洁"};
    String[] selectNR = new String[]{"正常", "异常"};

    String[] XJJG = new String[]{"设备现状", "是否存在"};

    private Map<String, String> mMapNR;//巡检内容
    private Map<String, String> mMapJG; //巡检结果

    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);
//        isFind = getIntent().getExtras().getBoolean("isFind");
        isDone = getIntent().getExtras().getBoolean("isDone");
        taskDtlId = getIntent().getExtras().getString("taskDtlId");
        isShow = getIntent().getExtras().getBoolean("isShow");
//        if (isShow) {
//            totalId = getIntent().getExtras().getString("totalId"); // z注意扫码进来是没有这个值的，且提交的时候不需要
//        } else {
//            //扫码进来的
//            qrCode = getIntent().getExtras().getString("qrCode");
//        }
        totalId = getIntent().getExtras().getString("totalId"); // z注意扫码进来是没有这个值的，且提交的时候不需要
        qrCode = getIntent().getExtras().getString("qrCode");
        //判断 是否符合UUID的规则
        if (null != qrCode && !"".equals(qrCode)) {
            if (!isUUID(qrCode)) {
                return;
            }
        }
        initDate();
        initListener();
        initRVAdapter();//初始化Adapter
        initObserve();

        pictureBean = new PictureBean();

        viewModel.selectDtl(totalId, taskDtlId, qrCode);
    }

    private void initDate() {
        mMapNR = new HashMap<>();
        mMapJG = new HashMap<>();
//        mListNR = new ArrayList<>();
//        mListJG = new ArrayList<>();
    }


    private void initObserve() {
        //上传图片先  然后上传详细信息
        viewModel.upload.observe(this, new Observer<LiveDataWrapper<UploadImgResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<UploadImgResponse> uploadImgResponseLiveDataWrapper) {
                switch (uploadImgResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(DeviceDetail2Activity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        if (null != uploadImgResponseLiveDataWrapper.data) {
                            if (TextUtils.isEmpty(uploadImgResponseLiveDataWrapper.data.getFileId()) || TextUtils.isEmpty(uploadImgResponseLiveDataWrapper.data.getThumbnailId())) {
                                ToastUtil.toastWarning(DeviceDetail2Activity.this, "图片上传失败，请重新尝试", -1);
                                if (null != imagePaths && imagePaths.size() > 0) {
                                    imagePaths.clear(); //清楚所有图片地址
                                    imagePaths = null;
                                }
                                isDelete = true;
                                isEdit = true;
                                imgRequest.setThumbnailId("");
                                imgRequest.setFileId("");
                                return;
                            }
                            imgRequest = uploadImgResponseLiveDataWrapper.data;
                        } else {
                            ToastUtil.toastWarning(DeviceDetail2Activity.this, "服务器出问题了，请重试", -1);
                            onBackPressed();
                        }

                        break;
                    case ERROR:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        handleException(uploadImgResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.getSubmit().observe(this, new Observer<LiveDataWrapper<InspectRecordControllerResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectRecordControllerResponse> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(DeviceDetail2Activity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        setResult(Constants.RESULT_OK);
                        finish();
                        break;
                    case ERROR:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        handleException(inspectionTaskControllerResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        viewModel.getSubmitByBroadcast().observe(this, new Observer<LiveDataWrapper<InspectRecordControllerResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectRecordControllerResponse> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(DeviceDetail2Activity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        qrCode = key;
                        isDone = false;
                        isShow = false;
                        taskDtlId = null;
                        if (null != qrCode && !"".equals(qrCode)) {
                            if (!isUUID(qrCode)) {
                                return;
                            }
                        }
                        viewModel.selectDtl(DeviceDetail2Activity.this.totalId, null, qrCode);
                        break;
                    case ERROR:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        handleException(inspectionTaskControllerResponseLiveDataWrapper.error, false);
                        break;
                }
            }
        });
        //根据图片ID获取图片前缀
        viewModel.photoUrl.observe(this, new Observer<LiveDataWrapper<String>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<String> responseBodyLiveDataWrapper) {
                switch (responseBodyLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(DeviceDetail2Activity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        if (null != responseBodyLiveDataWrapper.data) {
                            pictureBean.setThumbnailUrl(responseBodyLiveDataWrapper.data + imgRequest.getThumbnailId());
                            pictureBean.setPictureUrl(responseBodyLiveDataWrapper.data + imgRequest.getFileId());
                            viewModel.mDeviceDetailPhotoAdapter.setBitmaps(pictureBean);
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        handleException(responseBodyLiveDataWrapper.error, false);
                        finish();
                        break;
                }
            }
        });
        viewModel.getSelectDtl().observe(this, new Observer<LiveDataWrapper<InspectTaskSelect>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InspectTaskSelect> inspectionTaskControllerResponseLiveDataWrapper) {
                switch (inspectionTaskControllerResponseLiveDataWrapper.status) {
                    case LOADING:
                        DialogUtils.waitingDialog(DeviceDetail2Activity.this);
                        break;
                    case SUCCESS:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        if (null != inspectionTaskControllerResponseLiveDataWrapper.data && null != inspectionTaskControllerResponseLiveDataWrapper.data.getSingle()) {
                            InspectTaskSelect total = inspectionTaskControllerResponseLiveDataWrapper.data;
                            inspectTaskDtlVO = total.getSingle();

                            if (TextUtils.isEmpty(inspectTaskDtlVO.getThumbnailId())) {
                                binding.rvPhotos.setVisibility(View.GONE);
                            }
                            if (!TextUtils.isEmpty(inspectTaskDtlVO.getThumbnailId()) && !TextUtils.isEmpty(inspectTaskDtlVO.getPictureId())) {
                                imgRequest = new UploadImgResponse();
                                imgRequest.setThumbnailId(inspectTaskDtlVO.getThumbnailId());
                                imgRequest.setFileId(inspectTaskDtlVO.getPictureId());
                                viewModel.getPhotoUrl();
                            }

                            if (null != total.getMsg() && "当前资产不在巡检范围内".equals(total.getMsg())) {
                                commonUI(total.getSingle(), false);
                                return;
                            }
                            if (!isLocal) {
                                showUI(total.getSingle());
                            }
                        }
                        break;
                    case ERROR:
                        DialogUtils.dismiss(DeviceDetail2Activity.this);
                        handleException(inspectionTaskControllerResponseLiveDataWrapper.error, true);
                        finish();
                        break;
                }
            }
        });
    }

    private void initListener() {
        binding.deviceTitle.titleTextTv.setText("设备巡检详情");
        binding.deviceTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.deviceTitle.titleBackTv.setText("");
        binding.deviceTitle.titleBackLl.setOnClickListener(this);
        binding.deviceTitle.titleMenuConfirm.setText("保存");
        binding.deviceTitle.titleMenuConfirm.setOnClickListener(this);
        binding.rlSelect1.setOnClickListener(this);
        binding.rlSelect2.setOnClickListener(this);
        binding.rlSelect3.setOnClickListener(this);
        binding.rlSelect4.setOnClickListener(this);
        binding.tvLimit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageSelectorUtils.openPhoto(DeviceDetail2Activity.this, REQUEST_CODE, true, 1);
            }
        });
        binding.imgvAddPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageSelectorUtils.openPhoto(DeviceDetail2Activity.this, REQUEST_CODE, true, 1);
            }
        });
        //点击查看调出大图
        binding.tvLookDevicedetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getAssetsPictureIdUrl()) {
                    checkImgvPop.showAsDropDown(binding.rlLook);
                    AlphaManager.backgroundAlpha(0.7f, DeviceDetail2Activity.this);
                }
            }
        });
        // TODO:字数限制
        binding.remark.addTextChangedListener(new MyTextWatcher(binding.tvLimit,binding.remark, 50, DeviceDetail2Activity.this));
        binding.remark.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!v.getText().toString().equals(binding.remark.getText().toString())) {
                    isEdit = true;
                }
                return true;
            }
        });
    }

    private void initRVAdapter() {
        MLinearLayoutManager mLinearLayoutManager = new MLinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mLinearLayoutManager.setScrollEnabled(false);
        MLinearLayoutManager mLinearLayoutManager2 = new MLinearLayoutManager(this);
        mLinearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        mLinearLayoutManager2.setScrollEnabled(false);
        binding.rvPhotos.setLayoutManager(mLinearLayoutManager);
        binding.rvPhotos.setAdapter(viewModel.mDeviceDetailPhotoAdapter);
        if (isDone) {
            //显示 已完成的样式
            binding.remark.setVisibility(View.GONE);
            binding.imgvAddPhoto.setVisibility(View.GONE);
            binding.tvLimit.setVisibility(View.GONE);
            binding.rlLimit.setVisibility(View.GONE);

            binding.remarkDone.setVisibility(View.VISIBLE);
            binding.lineDone.setVisibility(View.VISIBLE);
            binding.rlXunjianTimeDone.setVisibility(View.VISIBLE);
            viewModel.mDeviceDetailPhotoAdapter.setDeleteGone(true); //去掉叉叉
        } else {
            //显示 未完成的样式
            binding.remark.setVisibility(View.VISIBLE);
            binding.imgvAddPhoto.setVisibility(View.VISIBLE);
            binding.tvLimit.setVisibility(View.VISIBLE);
            binding.rlLimit.setVisibility(View.VISIBLE);

            binding.remarkDone.setVisibility(View.GONE);
            binding.lineDone.setVisibility(View.GONE);
            binding.rlXunjianTimeDone.setVisibility(View.GONE);
            viewModel.mDeviceDetailPhotoAdapter.setDeleteGone(false); //去掉叉叉
        }
        viewModel.mDeviceDetailPhotoAdapter.setOnclickItemListener(new DeviceDetailPhotoAdapter.OnclickItemListener() {
            @Override
            public void delete() {
                if (null != imagePaths && imagePaths.size() > 0) {
                    imagePaths.clear(); //清楚所有图片地址
                    imagePaths = null;
                }
                isDelete = true;
                isEdit = true;
                imgRequest.setFileId("");
                imgRequest.setThumbnailId("");
            }

            @Override
            public void enlarge(String url) {
                if (null != url && !"".equals(url)) {
                    if (null == mStrings) {
                        mStrings = new ArrayList<>();
                    }
                    mStrings.clear();
                    mStrings.add(url);
                    mPhotoPreviewDialog = new PhotoPreviewDialog.Builder()
                            .needHeader(PreferenceManager.getInstance().getHeaderToken())
                            .index(0)
                            .path(mStrings)
                            .build();
                    mPhotoPreviewDialog.show(getSupportFragmentManager(), null);
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null && resultCode == Activity.RESULT_OK) {
            ArrayList<String> images = data.getStringArrayListExtra(ImageSelectorUtils.SELECT_RESULT);
            filePath = images.get(0);
            isLocal = true;
            isDelete = false;
            isEdit = true;
            //每次获取本地图片后进行压缩，因为压缩需要时间约1s,异步返回，保证一般情况下可以在保存操作之前压缩完成
            Tiny.FileCompressOptions options = new Tiny.FileCompressOptions();
            if (null == imagePaths) {
                imagePaths = new ArrayList<>();
            }
            imagePaths.clear();
//            imagePaths.add(filePath);

            Tiny.getInstance().source(filePath).asFile().withOptions(options).compress(new FileCallback() {
                @Override
                public void callback(boolean isSuccess, String outfile) {
                    if (isSuccess) {
                        imagePaths.add(outfile);

                        binding.rvPhotos.setVisibility(View.VISIBLE);
                        pictureBean.setThumbnailUrl(filePath);
                        pictureBean.setPictureUrl(filePath);
                        viewModel.mDeviceDetailPhotoAdapter.setBitmaps(pictureBean);
                        //直接上传图片
                        viewModel.uploadPic(imagePaths);
                    }
                }
            });


        }
    }


    private void setRemark() {
        binding.titleRemark.setText(Html.fromHtml(getString(R.string.divice_notice3)));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_detail2;
    }

    @Override
    public void onBackPressed() {
        if (isEdit) {
            mDialog = CreateDialog.infoDialog(DeviceDetail2Activity.this, "提醒", "该巡检详情还未保存，是否退出", "否", "是", v12 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                }
            }, v1 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                    setResult(Constants.RESULT_OK);
                    finish();
                }
            });
        } else {
            setResult(Constants.RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isDone) {
            closeBroadCast();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isDone) {
            openBroadCast();
        }
    }

    public boolean isUUID(String qrCode) {
        if (null != qrCode && !"".equals(qrCode)) {
            if (!MD5Util.IsUUID(qrCode)) {
                binding.main.setVisibility(View.GONE);
                binding.imgvUnknown.setVisibility(View.VISIBLE);
                binding.tvUnknown.setVisibility(View.VISIBLE);
                binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);
                binding.deviceTitle.titleTextTv.setText("错误");
                isFind = false;
                return false;
            }
        }
        return true;
    }

    public void commonUI(InspectTaskDtlVO inspectTaskDtlVO, boolean isFind) {
        this.isFind = isFind;
        binding.main.setVisibility(View.VISIBLE);
        binding.imgvUnknown.setVisibility(View.GONE);
        binding.tvUnknown.setVisibility(View.GONE);
        if (!isFind) {
            binding.rlNotFind.setVisibility(View.VISIBLE);
            binding.rlRemarkNodone.setVisibility(View.GONE);
            binding.deviceTitle.titleTextTv.setText("错误");
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);
        } else {
            binding.rlNotFind.setVisibility(View.GONE);
            binding.rlRemarkNodone.setVisibility(View.VISIBLE);
            binding.deviceTitle.titleTextTv.setText("设备巡检详情");
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        }
        if (null != inspectTaskDtlVO) {
            if (null != inspectTaskDtlVO.getCardNo()) {   //资产编码
                binding.tvCardNo.setText(inspectTaskDtlVO.getCardNo());
            }
            if (null != inspectTaskDtlVO.getCardName()) {  //资产名称
                binding.tvDeviceNameDevicedetail.setText(inspectTaskDtlVO.getCardName());
                binding.room.setText(inspectTaskDtlVO.getCardName());
            }
            if (null != inspectTaskDtlVO.getProduceNo()) {  //出场设备
                binding.tvProduceNo.setText(inspectTaskDtlVO.getProduceNo());
            }
            if (null != inspectTaskDtlVO.getInspectRecordDtlId()) {
                isSecond = true;
            }
        }

        // 查看按钮是否显示
        if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getAssetsPictureIdUrl() && !"".equals(inspectTaskDtlVO.getAssetsPictureIdUrl())) {
            binding.tvLookDevicedetail.setVisibility(View.VISIBLE);
            GlideUrl glideUrlHeaderUrl = viewModel.getGlideUrlHeaderUrl(inspectTaskDtlVO.getAssetsPictureIdUrl(), PreferenceManager.getInstance().getHeaderToken());
            checkImgvPop = new CheckImgvPop(DeviceDetail2Activity.this, glideUrlHeaderUrl);
        } else {
            binding.tvLookDevicedetail.setVisibility(View.GONE);
        }
    }

    public void showUI(InspectTaskDtlVO inspectTaskDtlVO) {

        commonUI(inspectTaskDtlVO, true);
        if (null == inspectTaskDtlVO.getFunctionStatus() || null == inspectTaskDtlVO.getAppearanceStatus()) {
            //说明是第一次进来编辑 也就是新增状态
            for (int i = 1; i <= XJNR.length; i++) {
                mMapNR.put(i + XJNR[i - 1], "y");
            }
            mMapJG.put("1设备现状", "y");
            mMapJG.put("2设备是否存在", "y");
        } else {
            //编辑状态
            if (null != inspectTaskDtlVO.getAppearanceStatus() && !TextUtils.isEmpty(inspectTaskDtlVO.getAppearanceStatus())) {
                mMapNR.put("1外观检查", inspectTaskDtlVO.getAppearanceStatus());
            }
            if (null != inspectTaskDtlVO.getLabelStatus() && !TextUtils.isEmpty(inspectTaskDtlVO.getLabelStatus())) {
                mMapNR.put("2标签齐全", inspectTaskDtlVO.getLabelStatus());
            }
            if (null != inspectTaskDtlVO.getFunctionStatus() && !TextUtils.isEmpty(inspectTaskDtlVO.getFunctionStatus())) {
                mMapNR.put("3功能检查", inspectTaskDtlVO.getFunctionStatus());
            }
            if (null != inspectTaskDtlVO.getCleanStatus() && !TextUtils.isEmpty(inspectTaskDtlVO.getCleanStatus())) {
                mMapNR.put("4设备清洁", inspectTaskDtlVO.getCleanStatus());
            }
            if (null != inspectTaskDtlVO.getAssetsStatus() && !TextUtils.isEmpty(inspectTaskDtlVO.getAssetsStatus())) {
                mMapJG.put("1设备现状", inspectTaskDtlVO.getAssetsStatus());
            }
            if(!isShow){
                mMapJG.put("2设备是否存在", "y");
            }else{
                if (null != inspectTaskDtlVO.getIsExist() && !TextUtils.isEmpty(inspectTaskDtlVO.getIsExist())) {
                    mMapJG.put("2设备是否存在", inspectTaskDtlVO.getIsExist());
                }
            }

//            if(notApply(mMapNR) == RESULT_FAIL || notApply(mMapJG) == RESULT_FAIL){
//                setRemark();
//            }
        }
        List<Map.Entry<String, String>> mMapNRList = new ArrayList<Map.Entry<String, String>>(mMapNR.entrySet());
        List<Map.Entry<String, String>> mMapJGList = new ArrayList<Map.Entry<String, String>>(mMapJG.entrySet());
        Collections.sort(mMapNRList, deviceComptor);
        Collections.sort(mMapJGList, deviceComptor);
        if (isDone) {
            //已完成的界面
            binding.resultSelect4.setText("");
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.GONE);
            addView(mMapNR, 2, 3, mMapNRList);
            addView(mMapJG, 3, 3, mMapJGList);
            //备注
            if (null != inspectTaskDtlVO.getRemarks()) {
                binding.remarkDone.setText(inspectTaskDtlVO.getRemarks().trim());
            } else {
                binding.remarkDone.setText("无");
            }
            //巡检时间
            if (null != inspectTaskDtlVO.getInspectDatetime()) {
                binding.checkTimeDone.setText(inspectTaskDtlVO.getInspectDatetime());
            } else {
                binding.checkTimeDone.setText("未知");
            }
        } else {
            //未完成的界面
            addView(mMapNR, 2, 2, mMapNRList);
            addView(mMapJG, 3, 2, mMapJGList);
            binding.deviceTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
            //设置状态 1.已经设置过状态 2.未设置过状态
            // 备注
            if (null != inspectTaskDtlVO.getRemarks()) {
                binding.remark.setText(inspectTaskDtlVO.getRemarks().trim());
                binding.remark.setSelection(binding.remark.getText().length());
            } else {
                binding.remark.setText("");
            }
        }
    }

    /**
     * 0 合格  1  不合格  2  不适用
     *
     * @param mList
     * @return
     */
    private int notApply(Map<String, String> mList) {
        for (Map.Entry<String, String> bean : mList.entrySet()) {
            if (!bean.getValue().equals("y")) {
                return RESULT_FAIL;
            }
        }
        return RESULT_OK;
    }

    private void addView(Map<String, String> mList, int type, int state, List<Map.Entry<String, String>> mMapList) {
        binding.include2.title.setText("巡检内容");
        binding.include3.title.setText("巡检结果");
        switch (notApply(mList)) {
            case RESULT_OK:
                if (type == 3) {
                    binding.include3.tvState.setText("正常");
                    binding.resultSelect3.setText("正常");
                } else {
                    binding.include2.tvState.setText("正常");
                    binding.resultSelect2.setText("正常");
                }
                break;
            case RESULT_FAIL:
                if (type == 3) {
                    binding.include3.tvState.setText("异常");
                    binding.resultSelect3.setText("异常");
                } else {
                    binding.include2.tvState.setText("异常");
                    binding.resultSelect2.setText("异常");
                }
                break;
        }
        for (Map.Entry<String, String> bean : mMapList) {
            String key = bean.getKey().substring(1);
            if (state == 3) {
                RelativeLayout mRl = (RelativeLayout) LayoutInflater.from(DeviceDetail2Activity.this).inflate(R.layout.iten_look_see, null);
                TextView mTextView = mRl.findViewById(R.id.tv_see);
                if (type == 3) {
                    if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(bean.getValue())) {
                        String value = "";
                        if (key.equals("设备现状")) {
                            switch (bean.getValue()) {
                                case "y":
                                    value = "正常";
                                    break;
                                case "n":
                                    value = "停用";
                                    break;
                                case "m":
                                    value = "维修";
                                    break;
                            }
                        } else {
                            switch (bean.getValue()) {
                                case "y":
                                    value = "是";
                                    break;
                                case "n":
                                    value = "否";
                                    break;
                            }
                        }
                        mTextView.setText(key + ":  " + value);
                    }
                } else {
                    if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(bean.getValue())) {
                        mTextView.setText(key + ":  " + (bean.getValue().equals("y") ? "正常" : "异常"));
                    }
                }
                if (type == 3) {
                    binding.include3.llTotal.addView(mRl);
                } else {
                    binding.include2.llTotal.addView(mRl);
                }
            } else {
                LinearLayout mRl = (LinearLayout) LayoutInflater.from(DeviceDetail2Activity.this).inflate(R.layout.item_device_psf, null);
                TextView mTextView = mRl.findViewById(R.id.title);
                TagFlowLayout tagFlowLayout = (mRl.findViewById(R.id.psResTF));
                tagFlowLayout.setMaxSelectCount(1);
                TagAdapter<String> tagAdapter = null;
                if (type == 3) {
                    if (!TextUtils.isEmpty(key)) {
                        mTextView.setText(key);
                    }
                    if (key.equals("设备现状")) {
                        tagAdapter = new TagAdapter<String>(Arrays.asList("正常", "停用", "维修")) {
                            @Override
                            public View getView(FlowLayout parent, int position, String s) {
                                TextView tv = (TextView) LayoutInflater.from(DeviceDetail2Activity.this).inflate(R.layout.item_tag_full, tagFlowLayout, false);
                                tv.setText(s);
                                return tv;
                            }
                        };
                    } else {
                        if (!isShow){
                            tagAdapter = new TagAdapter<String>(Collections.singletonList("是")) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(DeviceDetail2Activity.this).inflate(R.layout.item_tag_full, tagFlowLayout, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            };
                        }else{
                            tagAdapter = new TagAdapter<String>(Arrays.asList("是", "否")) {
                                @Override
                                public View getView(FlowLayout parent, int position, String s) {
                                    TextView tv = (TextView) LayoutInflater.from(DeviceDetail2Activity.this).inflate(R.layout.item_tag_full, tagFlowLayout, false);
                                    tv.setText(s);
                                    return tv;
                                }
                            };
                        }

                    }
                    tagFlowLayout.setAdapter(tagAdapter);
                    if (!TextUtils.isEmpty(key)) {
                        mTextView.setText(key);
                    }
                    if (!TextUtils.isEmpty(bean.getValue())) {
                        tagAdapter.setSelectedList(bean.getValue().equals("y") ? 0 : bean.getValue().equals("n") ? 1 : 2);
//                        if(key.equals("设备现状")){
//                            tagAdapter.setSelectedList(bean.getValue().equals("y") ? 0 : bean.getValue().equals("n") ? 1 : 2);
//                        }else{
//                            tagAdapter.setSelectedList(bean.getValue().equals("y") ? 0 : 1);
//                        }
                    }
                } else {
                    tagAdapter = new TagAdapter<String>(Arrays.asList("正常", "异常")) {
                        @Override
                        public View getView(FlowLayout parent, int position, String s) {
                            TextView tv = (TextView) LayoutInflater.from(DeviceDetail2Activity.this).inflate(R.layout.item_tag_full, tagFlowLayout, false);
                            tv.setText(s);
                            return tv;
                        }
                    };
                    tagFlowLayout.setAdapter(tagAdapter);
                    if (!TextUtils.isEmpty(key)) {
                        mTextView.setText(key);
                    }
                    if (!TextUtils.isEmpty(bean.getValue())) {
                        tagAdapter.setSelectedList(bean.getValue().equals("y") ? 0 : 1);
                    }
                }
                tagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                    @Override
                    public boolean onTagClick(View view, int position, FlowLayout parent) {
                        if (type == 3) {
                            if (((TagFlowLayout) parent).getSelectedList().size() == 0) {
                                mMapJG.remove(bean.getKey());
                            } else {
                                mMapJG.put(bean.getKey(), position == 0 ? "y" : position == 1 ? "n" : "m");
                            }
                            //若是外观检查 和 功能检查中的其中一个显示异常    则设备现状锁定为维修
                            if (mMapJG.containsKey("1设备现状") && (bean.getKey().equals("1设备现状") && position != 2 ) && isCheck(mMapNR)) {
                                mMapJG.put("1设备现状", "m");
                                ((TagFlowLayout) parent).getAdapter().setSelectedList(2);
                                ToastUtil.toastWarning(DeviceDetail2Activity.this, "外观或功能检查为异常,设备现状锁定为维修!", -1);
                            }
                            //若是  设备不存在，巡检内容全部显示为异常
                            if (mMapJG.containsKey("2设备是否存在") && bean.getKey().equals("2设备是否存在") && position == 1) {
                                for (int i = 1; i <= XJNR.length; i++) {
                                    mMapNR.put(i + XJNR[i - 1], "n");
                                }
                                mMapJG.put("1设备现状", "m");
                                binding.include3.llTotal.removeViews(1, 2);
                                List<Map.Entry<String, String>> mMapJGList = new ArrayList<Map.Entry<String, String>>(mMapJG.entrySet());
                                Collections.sort(mMapJGList, deviceComptor);
                                addView(mMapJG, 3, 2, mMapJGList);

                                binding.include2.llTotal.removeViews(1, 4);
                                List<Map.Entry<String, String>> mMapNRList = new ArrayList<Map.Entry<String, String>>(mMapNR.entrySet());
                                Collections.sort(mMapNRList, deviceComptor);
                                addView(mMapNR, 2, 2, mMapNRList);
                            }

                            String result = mMapJG.size() != 2 ? "待选择" : notApply(mList) == 0 ? "正常" : "异常";
                            binding.include3.tvState.setText(result);
                            binding.resultSelect3.setText(result);
                        } else {
                            if (((TagFlowLayout) parent).getSelectedList().size() == 0) {
                                mMapNR.remove(bean.getKey());
                            } else {
                                mMapNR.put(bean.getKey(), position == 0 ? "y" :  "n");
                            }
                            //若是外观检查 和 功能检查中的其中一个显示异常    则设备现状锁定为维修
                            if ((mMapNR.containsKey("1外观检查") && bean.getKey().equals("1外观检查") && position == 1) || (mMapNR.containsKey("3功能检查") && bean.getKey().equals("3功能检查") && position == 1)) {
                                mMapJG.put("1设备现状","m");
                                mMapJG.put("2设备是否存在","y");
                                binding.include3.llTotal.removeViews(1, 2);
                                List<Map.Entry<String, String>> mMapJGList = new ArrayList<Map.Entry<String, String>>(mMapJG.entrySet());
                                Collections.sort(mMapJGList, deviceComptor);
                                addView(mMapJG, 3, 2, mMapJGList);
                            }
                            //若是  设备不存在，巡检内容全部显示为异常
                            if(mMapJG.containsKey("2设备是否存在")){
                                if (mMapJG.get("2设备是否存在").equals("n")) {
                                    mMapNR.put(bean.getKey(), "n");
                                    tagFlowLayout.getAdapter().setSelectedList(1);
                                    ToastUtil.toastWarning(DeviceDetail2Activity.this, "当前设备不存在,已锁定为异常!", -1);
                                }
                            }
                            String result = mMapNR.size() != XJNR.length ? "待选择" : notApply(mList) == 0 ? "正常" : "异常";
                            binding.include2.tvState.setText(result);
                            binding.resultSelect2.setText(result);
                        }
//                        if(notApply(mMapNR) == RESULT_FAIL || notApply(mMapJG) == RESULT_FAIL){
//                            setRemark();
//                        }else{
//                            binding.titleRemark.setText("备注");
//                        }
//                        checkResult();
                        return true;
                    }
                });
                if (type == 3) {
                    binding.include3.llTotal.addView(mRl);
                } else {
                    binding.include2.llTotal.addView(mRl);
                }
            }
        }
    }

    //判断当前巡检内容Map中是否有外观异常或者功能检查异常
    public boolean isCheck(Map<String, String> map) {
        for (Map.Entry<String, String> bean : map.entrySet()) {
            if (bean.getKey().equals("1外观检查") || bean.getKey().equals("3功能检查")) {
                if (bean.getValue().equals("n")) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected Class<DeviceDetailViewModel> getViewModel() {
        return DeviceDetailViewModel.class;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back_ll:
                if (isEdit) {
                    mDialog = CreateDialog.infoDialog(DeviceDetail2Activity.this, "提醒", "该巡检详情还未保存，是否退出", "否", "是", v12 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                        }
                    }, v1 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                            setResult(Constants.RESULT_OK);
                            finish();
                        }
                    });
                } else {
                    setResult(Constants.RESULT_OK);
                    finish();
                }
                break;
            case R.id.title_menu_confirm:
                if (mMapNR.size() != XJNR.length || binding.include2.tvState.getText().equals("待选择")) {
                    showCheckFailedDialog("巡检内容检测模块有信息尚未选完,请选完保存");
                    return;
                }
                if (mMapJG.size() != 2 || binding.include3.tvState.getText().equals("待选择")) {
                    showCheckFailedDialog("巡检结果模块有信息尚未选完,请选完保存");
                    return;
                }
//                if (binding.titleRemark.getText().toString().contains("*") && 0 == binding.remark.getText().length()) {
//                    ToastUtil.toastWarning(DeviceDetail2Activity.this, "请添加备注说明", -1);
//                    return;
//                }
                viewModel.submitInspectRecord(submit());
                break;
            case R.id.rl_select_1:
                showAndHide(1);
                break;
            case R.id.rl_select_2:
                showAndHide(2);
                break;
            case R.id.rl_select_3:
                showAndHide(3);
                break;
            case R.id.rl_select_4:
                showAndHide(4);
                break;
        }
    }

    private void showAndHide(int type) {
        switch (type) {
            case 1:
                binding.include2.llTotal.setVisibility(View.GONE);
                binding.include3.llTotal.setVisibility(View.GONE);
                binding.include4.setVisibility(View.GONE);

                //自己是否显示，若显示则隐藏
                if (binding.card.getVisibility() == View.VISIBLE) {
                    binding.card.setVisibility(View.GONE);
                    binding.rlSelect1.setVisibility(View.VISIBLE);
                } else {
                    binding.card.setVisibility(View.VISIBLE);
                    binding.rlSelect1.setVisibility(View.GONE);
                    binding.rlSelect2.setVisibility(View.VISIBLE);
                    binding.rlSelect3.setVisibility(View.VISIBLE);
                    binding.rlSelect4.setVisibility(View.VISIBLE);
                }
                break;
            case 2:
                binding.card.setVisibility(View.GONE);
                binding.include3.llTotal.setVisibility(View.GONE);
                binding.include4.setVisibility(View.GONE);

                //自己是否显示，若显示则隐藏
                if (binding.include2.llTotal.getVisibility() == View.VISIBLE) {
                    binding.include2.llTotal.setVisibility(View.GONE);
                    binding.rlSelect2.setVisibility(View.VISIBLE);

                } else {
                    binding.include2.llTotal.setVisibility(View.VISIBLE);
                    binding.rlSelect1.setVisibility(View.VISIBLE);
                    binding.rlSelect2.setVisibility(View.GONE);
                    binding.rlSelect3.setVisibility(View.VISIBLE);
                    binding.rlSelect4.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
                binding.card.setVisibility(View.GONE);
                binding.include2.llTotal.setVisibility(View.GONE);
                binding.include4.setVisibility(View.GONE);

                //自己是否显示，若显示则隐藏
                if (binding.include3.llTotal.getVisibility() == View.VISIBLE) {
                    binding.include3.llTotal.setVisibility(View.GONE);
                    binding.rlSelect3.setVisibility(View.VISIBLE);
                } else {
                    binding.include3.llTotal.setVisibility(View.VISIBLE);
                    binding.rlSelect3.setVisibility(View.GONE);
                    binding.rlSelect1.setVisibility(View.VISIBLE);
                    binding.rlSelect2.setVisibility(View.VISIBLE);
                    binding.rlSelect4.setVisibility(View.VISIBLE);
                }
                break;
            case 4:
                binding.card.setVisibility(View.GONE);
                binding.include2.llTotal.setVisibility(View.GONE);
                binding.include3.llTotal.setVisibility(View.GONE);

                //自己是否显示，若显示则隐藏
                if (binding.include4.getVisibility() == View.VISIBLE) {
                    binding.include4.setVisibility(View.GONE);
                    binding.rlSelect4.setVisibility(View.VISIBLE);
                } else {
                    binding.include4.setVisibility(View.VISIBLE);
                    binding.rlSelect4.setVisibility(View.GONE);
                    binding.rlSelect3.setVisibility(View.VISIBLE);
                    binding.rlSelect1.setVisibility(View.VISIBLE);
                    binding.rlSelect2.setVisibility(View.VISIBLE);
                }
                break;
        }

    }

    private InspectRecordControllerRequest submit() {
        request = new InspectRecordControllerRequest();
        for (Map.Entry<String, String> bean : mMapNR.entrySet()) {
            String key = bean.getKey().substring(1);
            if (key.equals("外观检查")) {
                request.setAppearanceStatus(bean.getValue());
            }
            if (key.equals("标签齐全")) {
                request.setLabelStatus(bean.getValue());
            }
            if (key.equals("功能检查")) {
                request.setFunctionStatus(bean.getValue());
            }
            if (key.equals("设备清洁")) {
                request.setCleanStatus(bean.getValue());
            }
        }
        for (Map.Entry<String, String> bean : mMapJG.entrySet()) {
            String key = bean.getKey().substring(1);
            if (key.equals("设备现状")) {
                request.setAssetsStatus(bean.getValue());
            }
            if (key.equals("设备是否存在")) {
                request.setIsExist(bean.getValue());
            }
        }
        // remark 备注
        String remark = binding.remark.getText().toString().trim();
        String encode = null;
        try {
            encode = URLEncoder.encode(remark, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (remark.length() > 0) {
            request.setRemarks(encode);
        }
        if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getTaskDtlId()) {
            request.setTaskDtlId(inspectTaskDtlVO.getTaskDtlId());
        }
//                if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getBillId()) {
//                    request.setBillId(inspectTaskDtlVO.getBillId());
//                }
        if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getInspectRecordDtlId()) {
            request.setId(inspectTaskDtlVO.getInspectRecordDtlId());
        }
        if (isDelete && null == imagePaths) {
            request.setNoRemarksPic("y");
            if (null != inspectTaskDtlVO && null != inspectTaskDtlVO.getPictureId()) {
                request.setPictureId(inspectTaskDtlVO.getPictureId());
            }
        }
        if (null != totalId && !"".equals(totalId)) {
            request.setTaskId(totalId);
        } else if (null != qrCode && !"".equals(qrCode)) {
            request.setQrCode(qrCode);
            request.setTaskDtlId(null);
            request.setTaskId(null);
        }
        if (null != imgRequest) {
            request.setThumbnailId(imgRequest.getThumbnailId());
            request.setPictureId(imgRequest.getFileId());
        }
        return request;
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        key = msg;
        if (isFind) {
            if (!isEdit && isSecond) {
                //已经保存 并且 重复扫描同一个设备无操作，无需保存 直接跳入下一个设备
                qrCode = key;
                isDone = false;
                isShow = false;
                taskDtlId = null;
                if (null != qrCode && !"".equals(qrCode)) {
                    if (!isUUID(qrCode)) {
                        return;
                    }
                }
                viewModel.selectDtl(totalId, null, key);
            } else {
                if ("正常".equals(binding.resultSelect2.getText().toString()) && "正常".equals(binding.resultSelect3.getText().toString())) {
                    //默认保存
                    submit();
                    viewModel.submitInspectRecordBroad(request);
                } else {
                    //强提示去提交保存
                    CreateDialog.submitDialog(DeviceDetail2Activity.this, "提醒", "该巡检详情还未保存，请保存", 101, null, "确定");

                }
            }

        } else {
            // 巡检没找到的情况下，接着扫描
            qrCode = key;
            isDone = false;
            isShow = false;
            taskDtlId = null;
            if (null != qrCode && !"".equals(qrCode)) {
                if (!isUUID(qrCode)) {
                    return;
                }
            }
            viewModel.selectDtl(totalId, null, key);
        }

    }
}
